'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import diff from 'microdiff';
import type {
  IConfigPost,
  IDifference,
  IUpdatePostConfigBody,
} from '@/interfaces';
import type { TBody } from '@/types';
import { updatePostConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { ConfigAdminContext } from '@/contexts/admin/config';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateConfigPost({
  details,
}: {
  details: IConfigPost;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    enableCreateNotice?: boolean;
    enableUpdateNotice?: boolean;
    enableUpdateContentNotice?: boolean;
    enableUpdateStateNotice?: boolean;
  }>({
    enableCreateNotice: true,
    enableUpdateNotice: true,
    enableUpdateContentNotice: true,
    enableUpdateStateNotice: true,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();
  const context = useContext(ConfigAdminContext);

  const updatePostConfigMutation = useMutation(
    async (variables: TBody<IUpdatePostConfigBody>) => {
      await updatePostConfig(variables);
      await queryClient.invalidateQueries([
        '/configs',
        `/${context.updateItem?.id}`,
      ]);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        enableCreateNotice: details.enableCreateNotice,
        enableUpdateNotice: details.enableUpdateNotice,
        enableUpdateContentNotice: details.enableUpdateContentNotice,
        enableUpdateStateNotice: details.enableUpdateStateNotice,
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          enableCreateNotice: details.enableCreateNotice,
          enableUpdateNotice: details.enableUpdateNotice,
          enableUpdateContentNotice: details.enableUpdateContentNotice,
          enableUpdateStateNotice: details.enableUpdateStateNotice,
        },
        {
          enableCreateNotice: form.enableCreateNotice,
          enableUpdateNotice: form.enableUpdateNotice,
          enableUpdateContentNotice: form.enableUpdateContentNotice,
          enableUpdateStateNotice: form.enableUpdateStateNotice,
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (
      [
        'enableCreateNotice',
        'enableUpdateNotice',
        'enableUpdateContentNotice',
        'enableUpdateStateNotice',
      ].includes(name)
    ) {
      setForm({ ...form, [name]: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updatePostConfigMutation.mutateAsync({
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updatePostConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">启用创建通知</label>
            <select
              name="enableCreateNotice"
              value={form.enableCreateNotice ? 'true' : 'false'}
              onChange={onChangeForm}
              className="form-select"
              aria-label="enableCreateNotice"
              placeholder="请选择是否启用创建通知"
            >
              <option value="true">true</option>
              <option value="false">false</option>
            </select>
          </div>

          <div>
            <label className="form-label">启用更新通知</label>
            <select
              name="enableUpdateNotice"
              value={form.enableUpdateNotice ? 'true' : 'false'}
              onChange={onChangeForm}
              className="form-select"
              aria-label="enableUpdateNotice"
              placeholder="请选择是否启用更新通知"
            >
              <option value="true">true</option>
              <option value="false">false</option>
            </select>
          </div>

          <div>
            <label className="form-label">启用更新内容通知</label>
            <select
              name="enableUpdateContentNotice"
              value={form.enableUpdateContentNotice ? 'true' : 'false'}
              onChange={onChangeForm}
              className="form-select"
              aria-label="enableUpdateContentNotice"
              placeholder="请选择是否启用更新内容通知"
            >
              <option value="true">true</option>
              <option value="false">false</option>
            </select>
          </div>

          <div>
            <label className="form-label">启用更新状态通知</label>
            <select
              name="enableUpdateStateNotice"
              value={form.enableUpdateStateNotice ? 'true' : 'false'}
              onChange={onChangeForm}
              className="form-select"
              aria-label="enableUpdateStateNotice"
              placeholder="请选择是否启用更新状态通知"
            >
              <option value="true">true</option>
              <option value="false">false</option>
            </select>
          </div>

          <button
            type="submit"
            disabled={updatePostConfigMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updatePostConfigMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
